﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using VDS.RDF;
using VDS.RDF.Query;
using VDS.RDF.Storage;

namespace CoreVirtuoso
{
   internal static class QueryHelper
   {
      private static void EnableInferenceForQuery(ref string query, string reasonerRuleSet,
                                                  bool includeSparqlPrefix = false)
      {
         if (!String.IsNullOrEmpty(reasonerRuleSet))
            //query = "DEFINE input:inference \"" + reasonerRuleSet + "\"\n" +
            //        "DEFINE input:same-as \"yes\"\n" +
            //query;
            query = String.Format("DEFINE input:inference \"{0}\" {1}", reasonerRuleSet, query);
         if (includeSparqlPrefix)
            query = String.Format("sparql {0}", query);
      }

      #region Executing methods

      public static SparqlResultSet Query(IQueryableGenericIOManager virtuosoManager,
                                          string query,
                                          string reasonerRuleSet)
      {
         EnableInferenceForQuery(ref query, reasonerRuleSet);

         object results = virtuosoManager.Query(query);

         if (results == null)
            return null;
         if (!(results is SparqlResultSet))
            throw new Exception("Unexpected query result");

         return (SparqlResultSet) results;
      }

      public static object ExecuteScalar(VirtuosoManager virtuosoManager,
                                         string query,
                                         string reasonerRuleSet,
                                         bool includeSparqlPrefix = false)
      {
         EnableInferenceForQuery(ref query, reasonerRuleSet, includeSparqlPrefix);

         virtuosoManager.Open(true);
         object result = virtuosoManager.ExecuteScalar(query);
         virtuosoManager.Close(false);
         return result;
      }

      #endregion Execugin methods
   }
}